package com.zide.platform.controller;

import com.zide.auth.domain.entity.platform.PlatformUserRole;
import com.zide.auth.service.PlatformUserService;
import com.zide.auth.vo.result.PlatformUserResultVO;
import com.zide.auth.vo.search.PlatformRoleSearchVO;
import com.zide.auth.vo.search.PlatformUserSearchVO;
import com.zide.common.core.domain.CommonResult;
import com.zide.common.core.domain.PageResult;
import com.zide.platform.service.PlatformDeptService;
import com.zide.platform.service.PlatformPermissionService;
import com.zide.platform.service.PlatformRoleService;
import com.zide.platform.vo.result.role.PlatformRoleResultVO;
import com.zide.platform.vo.save.PlatformRoleSaveOrUpdateVO;
import com.zide.platform.vo.search.dept.PlatformDeptSearchVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import static com.zide.common.core.domain.CommonResult.*;

/**
 * @author 石添添
 * @description
 * @date 2024-09-22 14:29
 */
@Tag(name = "平台端角色管理")
@RestController
@RequestMapping("/platform/role")
@RequiredArgsConstructor
public class PlatformRoleController {
    
    private final PlatformRoleService roleService;

    private final PlatformPermissionService permissionService;

    private final PlatformUserService userService;

    private final PlatformDeptService deptService;

    @Operation(summary = "角色列表")
    @GetMapping("/list")
    public CommonResult list(PlatformRoleSearchVO searchVO) {
        PageResult<PlatformRoleResultVO> list = roleService.selectRolePage(searchVO);
        return success(list);
    }

    @Operation(summary = "根据角色编号获取详细信息")
    @GetMapping(value = "/{roleId}")
    public CommonResult getInfo(@PathVariable Long roleId) {
        roleService.checkRoleDataScope(roleId);
        return success(roleService.selectRoleById(roleId));
    }

    @Operation(summary = "新增角色")
    @PostMapping
    public CommonResult add(@Validated @RequestBody PlatformRoleSaveOrUpdateVO saveVO) {
        if (!roleService.checkRoleNameUnique(saveVO)) {
            return error("新增角色'" + saveVO.getRoleName() + "'失败，角色名称已存在");
        } else if (!roleService.checkRoleKeyUnique(saveVO)) {
            return error("新增角色'" + saveVO.getRoleName() + "'失败，角色权限已存在");
        }
        return getResult(roleService.insertRole(saveVO));

    }

    @Operation(summary = "修改角色")
    @PutMapping
    public CommonResult edit(@Validated @RequestBody PlatformRoleSaveOrUpdateVO saveVO) {
        roleService.checkRoleAllowed(saveVO);
        roleService.checkRoleDataScope(saveVO.getId());
        if (!roleService.checkRoleNameUnique(saveVO)) {
            return error("修改角色'" + saveVO.getRoleName() + "'失败，角色名称已存在");
        } else if (!roleService.checkRoleKeyUnique(saveVO)) {
            return error("修改角色'" + saveVO.getRoleName() + "'失败，角色权限已存在");
        }
        if (roleService.updateRole(saveVO) > 0) {
            // TODO 更新缓存用户权限
//            LoginUser loginUser = getLoginUser();
//            if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin()) {
//                loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser()));
//                PlatformtemUserResultVO PlatformtemUserResultVO = userService.selectUserByUserName(loginUser.getUser().getUsername());
//                loginUser.setUser(BeanUtil.copyProperties(PlatformtemUserResultVO, PlatformUser.class));
//                PlatformtemUserTokenUtil.setLoginUser(loginUser);
//            }
            return success();
        }
        return error("修改角色'" + saveVO.getRoleName() + "'失败，请联系管理员");
    }

    @Operation(summary = "修改保存数据权限")
    @PutMapping("/dataScope")
    public CommonResult dataScope(@RequestBody PlatformRoleSaveOrUpdateVO saveVO) {
        roleService.checkRoleAllowed(saveVO);
        roleService.checkRoleDataScope(saveVO.getId());
        return getResult(roleService.authDataScope(saveVO));
    }

    @Operation(summary = "状态修改")
    @PutMapping("/changeStatus")
    public CommonResult changeStatus(@RequestBody PlatformRoleSaveOrUpdateVO saveVO) {
        roleService.checkRoleAllowed(saveVO);
        roleService.checkRoleDataScope(saveVO.getId());
        return getResult(roleService.updateRoleStatus(saveVO));
    }

    @Operation(summary = "删除角色")
    @DeleteMapping("/{roleIds}")
    public CommonResult remove(@PathVariable Long[] roleIds) {
        return getResult(roleService.deleteRoleByIds(roleIds));
    }

    @Operation(summary = "获取角色选择框列表")
    @GetMapping("/optionselect")
    public CommonResult optionselect() {
        return success(roleService.selectRoleAll());
    }

    @Operation(summary = "查询已分配用户角色列表")
    @GetMapping("/authUser/allocatedList")
    public CommonResult allocatedList(PlatformUserSearchVO searchVO) {

        PageResult<PlatformUserResultVO> result = userService.selectAllocatedList(searchVO);
        return success(result);
    }

    @Operation(summary = "查询未分配用户角色列表")
    @GetMapping("/authUser/unallocatedList")
    public CommonResult unallocatedList(PlatformUserSearchVO searchVO) {
        PageResult<PlatformUserResultVO> result = userService.selectUnallocatedList(searchVO);
        return success(result);
    }

    @Operation(summary = "取消授权用户")
    @PutMapping("/authUser/cancel")
    public CommonResult cancelAuthUser(@RequestBody PlatformUserRole userRole) {
        return getResult(roleService.deleteAuthUser(userRole));
    }

    @Operation(summary = "批量取消授权用户")
    @PutMapping("/authUser/cancelAll")
    public CommonResult cancelAuthUserAll(Long roleId, Long[] userIds) {
        return getResult(roleService.deleteAuthUsers(roleId, userIds));
    }

    @Operation(summary = "批量选择用户授权")
    @PutMapping("/authUser/selectAll")
    public CommonResult selectAuthUserAll(Long roleId, Long[] userIds) {
        roleService.checkRoleDataScope(roleId);
        return getResult(roleService.insertAuthUsers(roleId, userIds));
    }

    @Operation(summary = "获取对应角色部门树列表")
    @GetMapping(value = "/deptTree/{roleId}")
    public CommonResult deptTree(@PathVariable("roleId") Long roleId) {
        CommonResult ajax = success();
        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", deptService.selectDeptTreeList(new PlatformDeptSearchVO()));
        return ajax;
    }
    
}
